<?php

namespace App\ZL\CrawlerExpansion;

use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\Remote\WebDriverCapabilityType;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverDimension;

class FileTool
{
    public static $driver=null;
    private static $connection_timeout_in_ms = 50000;
    private static $request_timeout_in_ms = 50000;
    private static $host = '127.0.0.1:8910';

    protected static function getDriver()
    {
        if(self::$driver==null){
            self::$driver = self::createDriver();
        }
        return self::$driver;
    }

    protected static function createDriver()
    {
        $capabilities = array(
            WebDriverCapabilityType::BROWSER_NAME => 'phantomjs',
            'phantomjs.page.settings.userAgent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0',
        );
        return RemoteWebDriver::create(self::$host, $capabilities, self::$connection_timeout_in_ms,self::$request_timeout_in_ms);
    }

    public function setWindowSize($x=1024,$y=768)
    {
        if(self::$driver==null){
            self::$driver = self::createDriver();
        }
        $window = new WebDriverDimension($x, $y);
        self::$driver->manage()->window()->setSize($window);
    }

    public function setTimeouts($a=300,$b=300,$c=300)
    {
        if(self::$driver==null){
            self::$driver = self::createDriver();
        }
        self::$driver->manage()->timeouts()->pageLoadTimeout($a)->implicitlyWait($b)->setScriptTimeout($c);
    }

    public static function screenShot($url,$fileSaveUri)
    {
        $driver = self::getDriver();
        //截图测试
        $driver->get($url);
        $driver->takeScreenshot($fileSaveUri);
//        $driver->quit();
    }

    public static function downloadJpg($url,$folder='./tmp/',$filename='')
    {
        $uri = $folder.($filename?$filename:self::getFileName($url));
//        dump($uri);
        $fp_output = fopen($uri, 'w');
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp_output);
        curl_exec($ch);
        curl_close($ch);

        exec("libreoffice ".$uri, $out, $status);
    }

    public static function checkHttpPrefix($url)
    {
        preg_match('/^http.*/',$url,$result);
        return isset($result[0])?true:false;
    }

    public static function getFileName($url)
    {
        preg_match('/^http.*\/(.+)\.(.+)/',$url,$result);
        if(isset($result[2])){
            return $result[1].'.'.$result[2];
        }else{
            return date('YmdHis').rand(10000,99999);
        }
    }
}